package com.ivi.car.module.city.presenter;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.promeg.pinyinhelper.Pinyin;
import com.ivi.car.R;
import com.ivi.car.module.city.model.CityInfo;
import com.ivi.car.module.city.model.SortModel;
import com.ivi.car.module.city.view.CityActivity;
import com.ivi.car.module.city.view.adapter.CityListAdapter;
import com.ivi.car.module.city.view.adapter.HotCityAdapter;
import com.ivi.car.module.city.view.util.HotGridView;
import com.ivi.car.module.city.view.util.PinyinComparator;
import com.ivi.car.module.city.view.util.SideBar;
import com.wm.machine.baselibrary.common.widget.recyclerview.itemdecoration.SpaceItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 选择城市presenter
 */

public class CityPresenter implements ICityPresenter {
    private final CityActivity mContext;
    private List<CityInfo> cityData = new ArrayList<>();
    private List<CityInfo> hotCityData = new ArrayList<>();
    private List<SortModel> sortList = new ArrayList<>();
    private final int topBottom = 10;
    private CityListAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private final int resultCode = 101;

    public CityPresenter(CityActivity cityActivity) {
        this.mContext = cityActivity;
    }

    /**
     * 展示热门城市
     *
     * @param gridView 展示热门城市控件
     */
    @Override
    public void showHotCity(HotGridView gridView) {
        hotCityData.add(new CityInfo("北京"));
        hotCityData.add(new CityInfo("上海"));
        hotCityData.add(new CityInfo("广州"));
        hotCityData.add(new CityInfo("重庆"));
        hotCityData.add(new CityInfo("深圳"));
        hotCityData.add(new CityInfo("长沙"));
        hotCityData.add(new CityInfo("天津"));
        hotCityData.add(new CityInfo("武汉"));

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        gridView.setAdapter(new HotCityAdapter(hotCityData, inflater));
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String selectName = hotCityData.get(position).getName();
                requestBack(selectName);
            }
        });
    }

    /**
     * 城市名字选择
     *
     * @param selectName 用户选择的城市名字
     */
    private void requestBack(String selectName) {
        Intent intent = mContext.getIntent();
        intent.putExtra("selectCity", selectName);
        mContext.setResult(resultCode, intent);
        mContext.finish();
    }

    /**
     * 显示城市数据
     *
     * @param cityList    RecyclerView用于显示城市的控件
     * @param headView    填充的头布局
     * @param citySlidBar 右侧字母显示控件
     */
    @Override
    public void showCityList(final RecyclerView cityList, View headView, SideBar citySlidBar) {
        setCityListData();
        setRecyclerView(cityList, headView);
        //右侧字母列表滑动监听
        citySlidBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int pos = adapter.getPositionForSection(s.charAt(0)) + 1;
                if (pos != 0 || s.equals("热门")) {
                    moveToPosition(pos, cityList);
                }
            }
        });

        cityList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (shouldScroll) {
                    shouldScroll = false;
                    moveToPosition(toPosition, cityList);
                }
            }
        });
    }

    /**
     * 创建城市假数据
     */
    private void setCityListData() {
        cityData.add(new CityInfo("北京"));
        cityData.add(new CityInfo("亳州"));
        cityData.add(new CityInfo("兖州市"));
        cityData.add(new CityInfo("上海"));
        cityData.add(new CityInfo("安阳"));
        cityData.add(new CityInfo("广州"));
        cityData.add(new CityInfo("重庆"));
        cityData.add(new CityInfo("深圳"));
        cityData.add(new CityInfo("长沙"));
        cityData.add(new CityInfo("天津"));
        cityData.add(new CityInfo("南京"));
        cityData.add(new CityInfo("青岛"));
        cityData.add(new CityInfo("钓鱼岛"));
        cityData.add(new CityInfo("杭州"));
        cityData.add(new CityInfo("宁波"));
        cityData.add(new CityInfo("台州"));
        cityData.add(new CityInfo("郑州"));
        cityData.add(new CityInfo("西安"));
        cityData.add(new CityInfo("洛阳"));
        cityData.add(new CityInfo("南阳"));
        cityData.add(new CityInfo("常州"));
        cityData.add(new CityInfo("嘉善"));
        cityData.add(new CityInfo("兰州"));
        cityData.add(new CityInfo("乌鲁木齐"));
    }

    private boolean shouldScroll;
    private int toPosition;

    /**
     * 根据位置recycleView移动到的位置
     *
     * @param pos      recycleView移动的位置
     * @param cityList recycleView控件
     */
    private void moveToPosition(int pos, final RecyclerView cityList) {
        int firstItem = cityList.getChildAdapterPosition(cityList.getChildAt(0));
        int lastItem = cityList.getChildAdapterPosition(cityList.getChildAt(cityList.getChildCount() - 1));
        if (pos < firstItem) {
            cityList.smoothScrollToPosition(pos);
        } else if (pos <= lastItem) {
            int movePosition = pos - firstItem;
            if (movePosition >= 0 && movePosition < cityList.getChildCount() - 1) {
                int top = cityList.getChildAt(movePosition).getTop();
                cityList.smoothScrollBy(0, top);
            }
        } else {
            cityList.smoothScrollToPosition(sortList.size());
            toPosition = pos;
            shouldScroll = true;
        }
    }

    /**
     * 添加recycleView头布局,设置recycleView
     *
     * @param cityList recycleView
     * @param headView 添加的头布局
     */
    private void setRecyclerView(RecyclerView cityList, View headView) {
        //添加数据首字母集合
        sortData();
        //进行排序数据比较
        PinyinComparator pinyinComparator = new PinyinComparator();
        Collections.sort(sortList, pinyinComparator);
        linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(0, topBottom);
        cityList.setLayoutManager(linearLayoutManager);
        cityList.addItemDecoration(spaceItemDecoration);
        adapter = new CityListAdapter(R.layout.item_city_selecter, sortList);
        adapter.addHeaderView(headView);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String name = sortList.get(position).getName();
                requestBack(name);
            }
        });
        cityList.setAdapter(adapter);
    }

    /**
     * 添加数据首字母集合
     */
    private void sortData() {
        for (int i = 0; i < cityData.size(); i++) {
            String name = cityData.get(i).getName();
            String pinyin = Pinyin.toPinyin(name, ",");
            SortModel sortModel = new SortModel();
            sortModel.setName(name);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            }
            sortList.add(sortModel);
        }
    }
}


